import { useEffect, useRef, useState } from 'react';
import { AddOutlined, Dialog, isArray } from 'esy-ui';
import { postBindBankList } from '@/services';
import { Empty } from '@/components';

function BindListDialog({ open, onClose, onSelected, id, token, onAdd }: any) {
  const [list, setList] = useState([]);
  const isQ = useRef(false);

  useEffect(() => {
    if (open && token && !isQ.current) {
      postBindBankList({})
        .then((res: any) => {
          if (isArray(res?.Data)) {
            setList(res?.Data.filter((it) => it.Pwtype === id));
            isQ.current = true;
          }
        })
        .catch(() => {});
    }
  }, [id, token, open]);

  return (
    <Dialog open={open} onClose={onClose} direction='bottom'>
      <div className='py-3 px-2.5 bg-white rounded-t-lg flex flex-col min-h-48'>
        <div className='flex-1 overflow-y-auto text-xs'>
          {isArray(list) ? (
            list.map((it, i) => (
              <div
                onClick={() => {
                  onSelected(it);
                }}
                className='py-2 px-3 my-2 border border-solid border-color-19 cursor-pointer hover:border-color-21 active:border-color-21'
                key={it.Id || i}
              >
                {`${it.BankName}`.slice(0, 4)}
                <span className='ml-2'>{it.AccountNo}</span>
              </div>
            ))
          ) : (
            <Empty />
          )}
        </div>
        <div className='border border-dashed border-color-21 py-2 cursor-pointer flex items-center justify-center mt-3' onClick={onAdd}>
          <AddOutlined className='text-sm text-color-21' />
        </div>
      </div>
    </Dialog>
  );
}

export default BindListDialog;
